home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1996 February: Tool Chest / Apple Developer CD Series Tool Chest February 1996 (Apple Computer)(1996).iso / Tool Chest / Files / XTND 1.3.6 / Application Examples / CSource / TESample.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-02-06  |  50.7 KB  |  1,603 lines  |  [TEXT/MPS ]

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple TextEdit Sample Application
  6. #
  7. #    TESample
  8. #
  9. #    This file: TESample.c    -    C Source
  10. #
  11. #    Copyright © 1989 Apple Computer, Inc.
  12. #    All rights reserved.
  13. #
  14. #    Versions:    
  15. #                1.00                08/88
  16. #                1.01                11/88
  17. #                1.02                04/89    MPW 3.1
  18. #
  19. #    Components:
  20. #                TESample.p            April 1, 1989
  21. #                TESample.c            April 1, 1989
  22. #                TESampleGlue.a        April 1, 1989
  23. #                TESample.r            April 1, 1989
  24. #                TESample.h            April 1, 1989
  25. #                [P]TESample.make    April 1, 1989
  26. #                [C]TESample.make    April 1, 1989
  27. #
  28. #    TESample is an example application that demonstrates how 
  29. #    to initialize the commonly used toolbox managers, operate 
  30. #    successfully under MultiFinder, handle desk accessories and 
  31. #    create, grow, and zoom windows. The fundamental TextEdit 
  32. #    toolbox calls and TextEdit autoscroll are demonstrated. It 
  33. #    also shows how to create and maintain scrollbar controls.
  34. #
  35. #    It does not by any means demonstrate all the techniques you 
  36. #    need for a large application. In particular, Sample does not 
  37. #    cover exception handling, multiple windows/documents, 
  38. #    sophisticated memory management, printing, or undo. All of 
  39. #    these are vital parts of a normal full-sized application.
  40. #
  41. #    This application is an example of the form of a Macintosh 
  42. #    application; it is NOT a template. It is NOT intended to be 
  43. #    used as a foundation for the next world-class, best-selling, 
  44. #    600K application. A stick figure drawing of the human body may 
  45. #    be a good example of the form for a painting, but that does not 
  46. #    mean it should be used as the basis for the next Mona Lisa.
  47. #
  48. #    We recommend that you review this program or Sample before 
  49. #    beginning a new application. Sample is a simple app. which doesn’t 
  50. #    use TextEdit or the Control Manager.
  51. #
  52. #-----------------------------------------------------------------------------*/
  53.  
  54.  
  55. /*----------------------------------------------------------------------*/
  56. /* XTND Note: This version of TESample has been modified to perform     */
  57. /*  all file read and write operations through XTND. The file            */
  58. /*  TE_FileIO.c has been added which contains the XTND import and        */
  59. /*  export functions XTNDInit, DoOpen, and DoSave, which are            */
  60. /*  called from this file. All changes made to this file to implement    */
  61. /*  XTND are marked with "•••"                                            */
  62. /*----------------------------------------------------------------------*/
  63.  
  64. /* ••• The following lines were added for XTND ••• */
  65.  
  66. #ifdef applec
  67.     #pragma load "MacIncludes"
  68. #endif
  69.  
  70. #ifndef __VALUES__
  71. #include <Values.h>
  72. #endif
  73.  
  74. #ifndef __TRAPS__
  75. #include <Traps.h>
  76. #endif
  77.  
  78. #include "TESample.h"
  79. #include ":::XTND Headers:XTNDCIncludes:XTNDInterface.h"
  80.  
  81. CursHandle    WATCH;
  82. void    XTNDInit(void);
  83. void    DoOpen(void);
  84. void    DoSave(Boolean);
  85.  
  86. /* ••• End of XTND additions ••• */
  87.  
  88.  
  89. /* Segmentation strategy:
  90.  
  91.    This program consists of three segments. Main contains most of the code,
  92.    including the MPW libraries, and the main program. Initialize contains
  93.    code that is only used once, during startup, and can be unloaded after the
  94.    program starts. %A5Init is automatically created by the Linker to initialize
  95.    globals for the MPW libraries and is unloaded right away. */
  96.  
  97.  
  98. /* SetPort strategy:
  99.  
  100.    Toolbox routines do not change the current port. In spite of this, in this
  101.    program we use a strategy of calling SetPort whenever we want to draw or
  102.    make calls which depend on the current port. This makes us less vulnerable
  103.    to bugs in other software which might alter the current port (such as the
  104.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  105.    Hopefully, this also makes the routines from this program more self-contained,
  106.    since they don't depend on the current port setting. */
  107.  
  108.  
  109. /* Clipboard strategy:
  110.  
  111.    This program does not maintain a private scrap. Whenever a cut, copy, or paste
  112.    occurs, we import/export from the public scrap to TextEdit's scrap right away,
  113.    using the TEToScrap and TEFromScrap routines. If we did use a private scrap,
  114.    the import/export would be in the activate/deactivate event and suspend/resume
  115.    event routines. */
  116.  
  117. /* A/UX is case sensitive, so use correct case for include file names */
  118.  
  119. /* The "g" prefix is used to emphasize that a variable is global. */
  120.  
  121. /* GMac is used to hold the result of a SysEnvirons call. This makes
  122.    it convenient for any routine to check the environment. It is
  123.    global information, anyway. */
  124. SysEnvRec    gMac;                /* set up by Initialize */
  125.  
  126. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  127.    trap is available. If it is false, we know that we must call GetNextEvent. */
  128. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  129.  
  130. /* GInBackground is maintained by our OSEvent handling routines. Any part of
  131.    the program can check it to find out if it is currently in the background. */
  132. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  133.  
  134. /* GNumDocuments is used to keep track of how many open documents there are
  135.    at any time. It is maintained by the routines that open and close documents. */
  136. short        gNumDocuments;        /* maintained by Initialize, DoNew, and DoCloseWindow */
  137.  
  138.  
  139. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  140.    actual prototypes for parameter type checking. A/UX C does not grok
  141.    prototypes, so eliminate them under A/UX */
  142.     void AlertUser( short error, short code );
  143.     void EventLoop( void );
  144.     void DoEvent( EventRecord *event );
  145.     void AdjustCursor( Point mouse, RgnHandle region );
  146.     void GetGlobalMouse( Point *mouse );
  147.     void DoGrowWindow( WindowPtr window, EventRecord *event );
  148.     void DoZoomWindow( WindowPtr window, short part );
  149.     void ResizeWindow( WindowPtr window );
  150.     void GetLocalUpdateRgn( WindowPtr window, RgnHandle localRgn );
  151.     void DoUpdate( WindowPtr window );
  152.     void DoDeactivate( WindowPtr window );
  153.     void DoActivate( WindowPtr window, Boolean becomingActive );
  154.     void DoContentClick( WindowPtr window, EventRecord *event );
  155.     void DoKeyDown( EventRecord *event );
  156.     unsigned long GetSleep( void );
  157.     void CommonAction( ControlHandle control, short *amount );
  158.     pascal void VActionProc( ControlHandle control, short part );
  159.     pascal void HActionProc( ControlHandle control, short part );
  160.     void DoIdle( void );
  161.     void DrawWindow( WindowPtr window );
  162.     void AdjustMenus( void );
  163.     void DoMenuCommand( long menuResult );
  164.     void DoNew( void );
  165.     Boolean DoCloseWindow( WindowPtr window );
  166.     void Terminate( void );
  167.     void Initialize( void );
  168.     void BigBadError( short error );
  169.     void GetTERect( WindowPtr window, Rect *teRect );
  170.     void AdjustTE( WindowPtr window );
  171.     void AdjustHV( Boolean isVert, ControlHandle control, TEHandle docTE, Boolean canRedraw );
  172.     void AdjustScrollValues( WindowPtr window, Boolean canRedraw );
  173.     void AdjustScrollSizes( WindowPtr window );
  174.     void AdjustScrollbars( WindowPtr window, Boolean needsResize );
  175.     pascal void PASCALCLIKLOOP( void );
  176.     pascal ProcPtr GETOLDCLIKLOOP( void );
  177.     Boolean IsAppWindow( WindowPtr window );
  178.     Boolean IsDAWindow( WindowPtr window );
  179.     Boolean TrapAvailable( short tNumber, TrapType tType );
  180.  
  181.  
  182. /* Define HiWrd and LoWrd macros for efficiency. */
  183. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  184. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  185.  
  186. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  187.    dependency on the ordering of fields within a Rect */
  188. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  189. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  190.  
  191.  
  192. /* This routine is part of the MPW runtime library. This external
  193.    reference to it is done so that we can unload its segment, %A5Init. */
  194.  
  195. #ifdef applec
  196. extern void _DataInit();
  197. #endif applec
  198.  
  199. /* A reference to our assembly language routine that gets attached to the clikLoop
  200. field of our TE record. */
  201.  
  202. extern pascal void ASMCLIKLOOP();
  203.  
  204. #pragma segment Main
  205. main()
  206. {
  207.     #ifdef applec
  208.         UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  209.     #endif applec
  210.     
  211.     /* 1.01 - call to ForceEnvirons removed */
  212.     
  213.     /*    If you have stack requirements that differ from the default,
  214.         then you could use SetApplLimit to increase StackSpace at 
  215.         this point, before calling MaxApplZone. */
  216.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  217.  
  218.     Initialize();                    /* initialize the program */
  219.  
  220.     #ifdef applec
  221.         UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  222.     #endif applec
  223.  
  224.     EventLoop();                    /* call the main event loop */
  225. }
  226.  
  227.  
  228. /* Get events forever, and handle them by calling DoEvent.
  229.    Also call AdjustCursor each time through the loop. */
  230.  
  231. void EventLoop()
  232. {
  233.     RgnHandle    cursorRgn;
  234.     Boolean        gotEvent;
  235.     EventRecord    event;
  236.  
  237.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  238.  
  239.     do {
  240.         /* use WNE if it is available */
  241.         if ( gHasWaitNextEvent ) {
  242.             gotEvent = WaitNextEvent(everyEvent, &event, GetSleep(), cursorRgn);
  243.         } else {
  244.             SystemTask();
  245.             gotEvent = GetNextEvent(everyEvent, &event);
  246.         }
  247.  
  248.         AdjustCursor(event.where, cursorRgn);
  249.  
  250.         if ( gotEvent )
  251.             DoEvent(&event);
  252.         else 
  253.             DoIdle();
  254.             
  255.         /*    If you are using modeless dialogs that have editText items,
  256.             you will want to call IsDialogEvent to give the caret a chance
  257.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  258.             for a non-NIL value before calling IsDialogEvent. */
  259.     } while ( true );    /* loop forever; we quit via ExitToShell */
  260.  
  261. } /*EventLoop*/
  262.  
  263.  
  264. /* Do the right thing for an event. Determine what kind of event it is, and call
  265.  the appropriate routines. */
  266.  
  267. void DoEvent(event)
  268.     EventRecord    *event;
  269. {
  270.     short        part, err;
  271.     WindowPtr    window;
  272.     char        key;
  273.     Point        aPoint;
  274.  
  275.     switch ( event->what ) {
  276.         case nullEvent:
  277.             /* we idle for null/mouse moved events ands for events which aren’t
  278.                 ours (see EventLoop) */
  279.             DoIdle();
  280.             break;
  281.         case mouseDown:
  282.             part = FindWindow(event->where, &window);
  283.             switch ( part ) {
  284.                 case inMenuBar:             /* process a mouse menu command (if any) */
  285.                     AdjustMenus();    /* bring ’em up-to-date */
  286.                     DoMenuCommand(MenuSelect(event->where));
  287.                     break;
  288.                 case inSysWindow:           /* let the system handle the mouseDown */
  289.                     SystemClick(event, window);
  290.                     break;
  291.                 case inContent:
  292.                     if ( window != FrontWindow() ) {
  293.                         SelectWindow(window);
  294.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  295.                     } else
  296.                         DoContentClick(window, event);
  297.                     break;
  298.                 case inDrag:            /* pass screenBits.bounds to get all gDevices */
  299.                     DragWindow(window, event->where, &screenBits.bounds);
  300.                     break;
  301.                 case inGoAway:
  302.                     if ( TrackGoAway(window, event->where) )
  303.                         DoCloseWindow(window); /* we don’t care if the user cancelled */
  304.                     break;
  305.                 case inGrow:
  306.                     DoGrowWindow(window, event);
  307.                     break;
  308.                 case inZoomIn:
  309.                 case inZoomOut:
  310.                 if ( TrackBox(window, event->where, part) )
  311.                         DoZoomWindow(window, part);
  312.                     break;
  313.             }
  314.             break;
  315.         case keyDown:
  316.         case autoKey:                       /* check for menukey equivalents */
  317.             key = event->message & charCodeMask;
  318.             if ( event->modifiers & cmdKey ) {    /* Command key down */
  319.                 if ( event->what == keyDown ) {
  320.                     AdjustMenus();            /* enable/disable/check menu items properly */
  321.                     DoMenuCommand(MenuKey(key));
  322.                 }
  323.             } else
  324.                 DoKeyDown(event);
  325.             break;
  326.         case activateEvt:
  327.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  328.             break;
  329.         case updateEvt:
  330.             DoUpdate((WindowPtr) event->message);
  331.             break;
  332.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  333.             to a diskEvt, so that the user can format a floppy. */
  334.         case diskEvt:
  335.             if ( HiWord(event->message) != noErr ) {
  336.                 SetPt(&aPoint, kDILeft, kDITop);
  337.                 err = DIBadMount(aPoint, event->message);
  338.             }
  339.             break;
  340.         case kOSEvent:
  341.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  342.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  343.                 case kMouseMovedMessage:
  344.                     DoIdle();                    /* mouse-moved is also an idle event */
  345.                     break;
  346.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  347.                     gInBackground = (event->message & kResumeMask) == 0;
  348.                     DoActivate(FrontWindow(), !gInBackground);
  349.                     break;
  350.             }
  351.             break;
  352.     }
  353. } /*DoEvent*/
  354.  
  355.  
  356. /*    Change the cursor's shape, depending on its position. This also calculates the region
  357.     where the current cursor resides (for WaitNextEvent). When the mouse moves outside of
  358.     this region, an event is generated. If there is more to the event than just
  359.     “the mouse moved”, we get called before the event is processed to make sure
  360.     the cursor is the right one. In any (ahem) event, this is called again before we
  361.     fall back into WNE. */
  362.  
  363. void AdjustCursor(mouse,region)
  364.     Point        mouse;
  365.     RgnHandle    region;
  366. {
  367.     WindowPtr    window;
  368.     RgnHandle    arrowRgn;
  369.     RgnHandle    iBeamRgn;
  370.     Rect        iBeamRect;
  371.  
  372.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  373.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  374.         /* calculate regions for different cursor shapes */
  375.         arrowRgn = NewRgn();
  376.         iBeamRgn = NewRgn();
  377.  
  378.         /* start arrowRgn wide open */
  379.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  380.  
  381.         /* calculate iBeamRgn */
  382.         if ( IsAppWindow(window) ) {
  383.             iBeamRect = (*((DocumentPeek) window)->docTE)->viewRect;
  384.             SetPort(window);    /* make a global version of the viewRect */
  385.             LocalToGlobal(&TopLeft(iBeamRect));
  386.             LocalToGlobal(&BotRight(iBeamRect));
  387.             RectRgn(iBeamRgn, &iBeamRect);
  388.             /* we temporarily change the port’s origin to “globalfy” the visRgn */
  389.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  390.             SectRgn(iBeamRgn, window->visRgn, iBeamRgn);
  391.             SetOrigin(0, 0);
  392.         }
  393.  
  394.         /* subtract other regions from arrowRgn */
  395.         DiffRgn(arrowRgn, iBeamRgn, arrowRgn);
  396.  
  397.         /* change the cursor and the region parameter */
  398.         if ( PtInRgn(mouse, iBeamRgn) ) {
  399.             SetCursor(*GetCursor(iBeamCursor));
  400.             CopyRgn(iBeamRgn, region);
  401.         } else {
  402.             SetCursor(&arrow);
  403.             CopyRgn(arrowRgn, region);
  404.         }
  405.  
  406.         DisposeRgn(arrowRgn);
  407.         DisposeRgn(iBeamRgn);
  408.     }
  409. } /*AdjustCursor*/
  410.  
  411.  
  412. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  413.     it will return either a pending event or a null event. In either case,
  414.     the where field of the event record will contain the current position
  415.     of the mouse in global coordinates and the modifiers field will reflect
  416.     the current state of the modifiers. Another way to get the global
  417.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  418.     being sure that thePort is set to a valid port. */
  419.  
  420. void GetGlobalMouse(mouse)
  421.     Point    *mouse;
  422. {
  423.     EventRecord    event;
  424.     
  425.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  426.     *mouse = event.where;                /* just the mouse position */
  427. } /*GetGlobalMouse*/
  428.  
  429.  
  430. /*    Called when a mouseDown occurs in the grow box of an active window. In
  431.     order to eliminate any 'flicker', we want to invalidate only what is
  432.     necessary. Since ResizeWindow invalidates the whole portRect, we save
  433.     the old TE viewRect, intersect it with the new TE viewRect, and
  434.     remove the result from the update region. However, we must make sure
  435.     that any old update region that might have been around gets put back. */
  436.  
  437. void DoGrowWindow(window,event)
  438.     WindowPtr    window;
  439.     EventRecord    *event;
  440. {
  441.     long        growResult;
  442.     Rect        tempRect;
  443.     RgnHandle    tempRgn;
  444.     DocumentPeek doc;
  445.     
  446.     tempRect = screenBits.bounds;                    /* set up limiting values */
  447.     tempRect.left = kMinDocDim;
  448.     tempRect.top = kMinDocDim;
  449.     growResult = GrowWindow(window, event->where, &tempRect);
  450.     /* see if it really changed size */
  451.     if ( growResult != 0 ) {
  452.         doc = (DocumentPeek) window;
  453.         tempRect = (*doc->docTE)->viewRect;                /* save old text box */
  454.         tempRgn = NewRgn();
  455.         GetLocalUpdateRgn(window, tempRgn);                /* get localized update region */
  456.         SizeWindow(window, LoWrd(growResult), HiWrd(growResult), true);
  457.         ResizeWindow(window);
  458.         /* calculate & validate the region that hasn’t changed so it won’t get redrawn */
  459.         SectRect(&tempRect, &(*doc->docTE)->viewRect, &tempRect);
  460.         ValidRect(&tempRect);                            /* take it out of update */
  461.         InvalRgn(tempRgn);                                /* put back any prior update */
  462.         DisposeRgn(tempRgn);
  463.     }
  464. } /* DoGrowWindow */
  465.  
  466.  
  467. /*     Called when a mouseClick occurs in the zoom box of an active window.
  468.     Everything has to get re-drawn here, so we don't mind that
  469.     ResizeWindow invalidates the whole portRect. */
  470.  
  471. void DoZoomWindow(window,part)
  472.     WindowPtr    window;
  473.     short        part;
  474. {
  475.     EraseRect(&window->portRect);
  476.     ZoomWindow(window, part, window == FrontWindow());
  477.     ResizeWindow(window);
  478. } /*  DoZoomWindow */
  479.  
  480.  
  481. /* Called when the window has been resized to fix up the controls and content. */
  482. void ResizeWindow(window)
  483.     WindowPtr    window;
  484. {
  485.     AdjustScrollbars(window, true);
  486.     AdjustTE(window);
  487.     InvalRect(&window->portRect);
  488. } /* ResizeWindow */
  489.  
  490.  
  491. /* Returns the update region in local coordinates */
  492. void GetLocalUpdateRgn(window,localRgn)
  493.     WindowPtr    window;
  494.     RgnHandle    localRgn;
  495. {
  496.     CopyRgn(((WindowPeek) window)->updateRgn, localRgn);    /* save old update region */
  497.     OffsetRgn(localRgn, window->portBits.bounds.left, window->portBits.bounds.top);
  498. } /* GetLocalUpdateRgn */
  499.  
  500.  
  501. /*    This is called when an update event is received for a window.
  502.     It calls DrawWindow to draw the contents of an application window.
  503.     As an efficiency measure that does not have to be followed, it
  504.     calls the drawing routine only if the visRgn is non-empty. This
  505.     will handle situations where calculations for drawing or drawing
  506.     itself is very time-consuming. */
  507.  
  508. void DoUpdate(window)
  509.     WindowPtr    window;
  510. {
  511.     if ( IsAppWindow(window) ) {
  512.         BeginUpdate(window);                /* this sets up the visRgn */
  513.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  514.             DrawWindow(window);
  515.         EndUpdate(window);
  516.     }
  517. } /*DoUpdate*/
  518.  
  519.  
  520. /*    This is called when a window is activated or deactivated.
  521.     It calls TextEdit to deal with the selection. */
  522.  
  523. void DoActivate(window, becomingActive)
  524.     WindowPtr    window;
  525.     Boolean        becomingActive;
  526. {
  527.     RgnHandle    tempRgn, clipRgn;
  528.     Rect        growRect;
  529.     DocumentPeek doc;
  530.     
  531.     if ( IsAppWindow(window) ) {
  532.         doc = (DocumentPeek) window;
  533.         if ( becomingActive ) {
  534.             /*    since we don’t want TEActivate to draw a selection in an area where
  535.                 we’re going to erase and redraw, we’ll clip out the update region
  536.                 before calling it. */
  537.             tempRgn = NewRgn();
  538.             clipRgn = NewRgn();
  539.             GetLocalUpdateRgn(window, tempRgn);            /* get localized update region */
  540.             GetClip(clipRgn);
  541.             DiffRgn(clipRgn, tempRgn, tempRgn);            /* subtract updateRgn from clipRgn */
  542.             SetClip(tempRgn);
  543.             TEActivate(doc->docTE);
  544.             SetClip(clipRgn);                            /* restore the full-blown clipRgn */
  545.             DisposeRgn(tempRgn);
  546.             DisposeRgn(clipRgn);
  547.             
  548.             /* the controls must be redrawn on activation: */
  549.             (*doc->docVScroll)->contrlVis = kControlVisible;
  550.             (*doc->docHScroll)->contrlVis = kControlVisible;
  551.             InvalRect(&(*doc->docVScroll)->contrlRect);
  552.             InvalRect(&(*doc->docHScroll)->contrlRect);
  553.             /* the growbox needs to be redrawn on activation: */
  554.             growRect = window->portRect;
  555.             /* adjust for the scrollbars */
  556.             growRect.top = growRect.bottom - kScrollbarAdjust;
  557.             growRect.left = growRect.right - kScrollbarAdjust;
  558.             InvalRect(&growRect);
  559.         }
  560.         else {        
  561.             TEDeactivate(doc->docTE);
  562.             /* the controls must be hidden on deactivation: */
  563.             HideControl(doc->docVScroll);
  564.             HideControl(doc->docHScroll);
  565.             /* the growbox should be changed immediately on deactivation: */
  566.             DrawGrowIcon(window);
  567.         }
  568.     }
  569. } /*DoActivate*/
  570.  
  571.  
  572. /*    This is called when a mouseDown occurs in the content of a window. */
  573.  
  574. void DoContentClick(window,event)
  575.     WindowPtr    window;
  576.     EventRecord    *event;
  577. {
  578.     Point        mouse;
  579.     ControlHandle control;
  580.     short        part, value;
  581.     Boolean        shiftDown;
  582.     DocumentPeek doc;
  583.     Rect        teRect;
  584.  
  585.     if ( IsAppWindow(window) ) {
  586.         SetPort(window);
  587.         mouse = event->where;                            /* get the click position */
  588.         GlobalToLocal(&mouse);
  589.         doc = (DocumentPeek) window;
  590.         /* see if we are in the viewRect. if so, we won’t check the controls */
  591.         GetTERect(window, &teRect);
  592.         if ( PtInRect(mouse, &teRect) ) {
  593.             /* see if we need to extend the selection */
  594.             shiftDown = (event->modifiers & shiftKey) != 0;    /* extend if Shift is down */
  595.             TEClick(mouse, shiftDown, doc->docTE);
  596.         } else {
  597.             part = FindControl(mouse, window, &control);
  598.             switch ( part ) {
  599.                 case 0:                            /* do nothing for viewRect case */
  600.                     break;
  601.                 case inThumb:
  602.                     value = GetCtlValue(control);
  603.                     part = TrackControl(control, mouse, nil);
  604.                     if ( part != 0 ) {
  605.                         value -= GetCtlValue(control);
  606.                         /* value now has CHANGE in value; if value changed, scroll */
  607.                         if ( value != 0 )
  608.                             if ( control == doc->docVScroll )
  609.                                 TEScroll(0, value, doc->docTE);
  610.                             else
  611.                                 TEScroll(value, 0, doc->docTE);
  612.                     }
  613.                     break;
  614.                 default:                        /* they clicked in an arrow, so track & scroll */
  615.                     if ( control == doc->docVScroll )
  616.                         value = TrackControl(control, mouse, (ProcPtr) VActionProc);
  617.                     else
  618.                         value = TrackControl(control, mouse, (ProcPtr) HActionProc);
  619.                     break;
  620.             }
  621.         }
  622.     }
  623. } /*DoContentClick*/
  624.  
  625.  
  626. /* This is called for any keyDown or autoKey events, except when the
  627.  Command key is held down. It looks at the frontmost window to decide what
  628.  to do with the key typed. */
  629.  
  630. void DoKeyDown(event)
  631.     EventRecord    *event;
  632. {
  633.     WindowPtr    window;
  634.     char        key;
  635.     TEHandle    te;
  636.  
  637.     window = FrontWindow();
  638.     if ( IsAppWindow(window) ) {
  639.         te = ((DocumentPeek) window)->docTE;
  640.         key = event->message & charCodeMask;
  641.         /* we have a char. for our window; see if we are still below TextEdit’s
  642.             limit for the number of characters (but deletes are always rad) */
  643.         if ( key == kDelChar ||
  644.                 (*te)->teLength - ((*te)->selEnd - (*te)->selStart) + 1 <
  645.                 kMaxTELength ) {
  646.             TEKey(key, te);
  647.             AdjustScrollbars(window, false);
  648.             AdjustTE(window);
  649.         } else
  650.             AlertUser(eExceedChar,0);
  651.     }
  652. } /*DoKeyDown*/
  653.  
  654.  
  655. /*    Calculate a sleep value for WaitNextEvent. This takes into account the things
  656.     that DoIdle does with idle time. */
  657.  
  658. unsigned long GetSleep()
  659. {
  660.     long        sleep;
  661.     WindowPtr    window;
  662.     TEHandle    te;
  663.  
  664.     sleep = MAXLONG;                        /* default value for sleep */
  665.     if ( !gInBackground ) {
  666.         window = FrontWindow();            /* and the front window is ours... */
  667.         if ( IsAppWindow(window) ) {
  668.             te = ((DocumentPeek) (window))->docTE;    /* and the selection is an insertion point... */
  669.             if ( (*te)->selStart == (*te)->selEnd )
  670.                 sleep = GetCaretTime();        /* blink time for the insertion point */
  671.         }
  672.     }
  673.     return sleep;
  674. } /*GetSleep*/
  675.  
  676.  
  677. /*    Common algorithm for pinning the value of a control. It returns the actual amount
  678.     the value of the control changed. Note the pinning is done for the sake of returning
  679.     the amount the control value changed. */
  680.  
  681. void CommonAction(control,amount)
  682.     ControlHandle control;
  683.     short        *amount;
  684. {
  685.     short        value, max;
  686.     
  687.     value = GetCtlValue(control);    /* get current value */
  688.     max = GetCtlMax(control);        /* and maximum value */
  689.     *amount = value - *amount;
  690.     if ( *amount < 0 )
  691.         *amount = 0;
  692.     else if ( *amount > max )
  693.         *amount = max;
  694.     SetCtlValue(control, *amount);
  695.     *amount = value - *amount;        /* calculate the real change */
  696. } /* CommonAction */
  697.  
  698.  
  699. /* Determines how much to change the value of the vertical scrollbar by and how
  700.     much to scroll the TE record. */
  701.  
  702. pascal void VActionProc(control,part)
  703.     ControlHandle control;
  704.     short        part;
  705. {
  706.     short        amount;
  707.     WindowPtr    window;
  708.     TEPtr        te;
  709.     
  710.     if ( part != 0 ) {                /* if it was actually in the control */
  711.         window = (*control)->contrlOwner;
  712.         te = *((DocumentPeek) window)->docTE;
  713.         switch ( part ) {
  714.             case inUpButton:
  715.             case inDownButton:        /* one line */
  716.                 amount = kButtonScroll;
  717.                 break;
  718.             case inPageUp:            /* one page minus overlap */
  719.             case inPageDown:
  720.                 amount = (te->viewRect.bottom - te->viewRect.top - 16);
  721.                 break;
  722.         }
  723.         if ( (part == inDownButton) || (part == inPageDown) )
  724.             amount = -amount;        /* reverse direction for a downer */
  725.         CommonAction(control, &amount);
  726.         if ( amount != 0 )
  727.             TEScroll(0, amount, ((DocumentPeek) window)->docTE);
  728.     }
  729. } /* VActionProc */
  730.  
  731.  
  732. /* Determines how much to change the value of the horizontal scrollbar by and how
  733. much to scroll the TE record. */
  734.  
  735. pascal void HActionProc(control,part)
  736.     ControlHandle control;
  737.     short        part;
  738. {
  739.     short        amount;
  740.     WindowPtr    window;
  741.     TEPtr        te;
  742.     
  743.     if ( part != 0 ) {
  744.         window = (*control)->contrlOwner;
  745.         te = *((DocumentPeek) window)->docTE;
  746.         switch ( part ) {
  747.             case inUpButton:
  748.             case inDownButton:        /* a few pixels */
  749.                 amount = kButtonScroll;
  750.                 break;
  751.             case inPageUp:            /* a page minus overlap */
  752.             case inPageDown:
  753.                 amount = te->viewRect.right - te->viewRect.left - 16;
  754.                 break;
  755.         }
  756.         if ( (part == inDownButton) || (part == inPageDown) )
  757.             amount = -amount;        /* reverse direction */
  758.         CommonAction(control, &amount);
  759.         if ( amount != 0 )
  760.             TEScroll(amount, 0, ((DocumentPeek) window)->docTE);
  761.     }
  762. } /* VActionProc */
  763.  
  764.  
  765. /* This is called whenever we get a null event et al.
  766.  It takes care of necessary periodic actions. For this program, it calls TEIdle. */
  767.  
  768. void DoIdle()
  769. {
  770.     WindowPtr    window;
  771.  
  772.     window = FrontWindow();
  773.     if ( IsAppWindow(window) )
  774.         TEIdle(((DocumentPeek) window)->docTE);
  775. } /*DoIdle*/
  776.  
  777.  
  778. /* Draw the contents of an application window. */
  779.  
  780. void DrawWindow(window)
  781.     WindowPtr    window;
  782. {
  783.     SetPort(window);
  784.     EraseRect(&window->portRect);
  785.     DrawControls(window);
  786.     DrawGrowIcon(window);
  787.     TEUpdate(&window->portRect, ((DocumentPeek) window)->docTE);
  788. } /*DrawWindow*/
  789.  
  790.  
  791. /*    Enable and disable menus based on the current state.
  792.     The user can only select enabled menu items. We set up all the menu items
  793.     before calling MenuSelect or MenuKey, since these are the only times that
  794.     a menu item can be selected. Note that MenuSelect is also the only time
  795.     the user will see menu items. This approach to deciding what enable/
  796.     disable state a menu item has the advantage of concentrating all
  797.     the decision-making in one routine, as opposed to being spread throughout
  798.     the application. Other application designs may take a different approach
  799.     that may or may not be as valid. */
  800.  
  801. void AdjustMenus()
  802. {
  803.     WindowPtr    window;
  804.     MenuHandle    menu;
  805.     long        offset;
  806.     Boolean        undo;
  807.     Boolean        cutCopyClear;
  808.     Boolean        paste;
  809.     TEHandle    te;
  810.     TextStyle    theStyle;
  811.     short        loop, lHeight, lAscent, font_num;
  812.     long        items;
  813.     Str255        theName;
  814.  
  815.     window = FrontWindow();
  816.  
  817.     menu = GetMHandle(mFile);
  818.  
  819.     if ( gNumDocuments < kMaxOpenDocuments )
  820.     {
  821.         EnableItem(menu, iOpen);
  822.         EnableItem(menu, iNew);        /* Open and new is enabled when we can open more documents */
  823.     }
  824.     else
  825.     {
  826.         DisableItem(menu, iOpen);
  827.         DisableItem(menu, iNew);
  828.     }
  829.  
  830.     if (IsAppWindow(window))
  831.     {
  832. #        ifdef qSAVE_WORKING_AND_DOC_DIRTY
  833.             EnableItem(menu, iSave);
  834. #        else
  835.             DisableItem(menu, iSave);
  836. #        endif qSAVE_WORKING_AND_DOC_DIRTY
  837.         EnableItem(menu, iSaveAs);
  838.     }
  839.     else
  840.     {
  841.         DisableItem(menu, iSave);
  842.         DisableItem(menu, iSaveAs);
  843.     }
  844.  
  845.     if ( window != nil )            /* Close is enabled when there is a window to close */
  846.         EnableItem(menu, iClose);
  847.     else
  848.         DisableItem(menu, iClose);
  849.  
  850.     menu = GetMHandle(mEdit);
  851.     undo = false;
  852.     cutCopyClear = false;
  853.     paste = false;
  854.     if ( IsDAWindow(window) ) {
  855.         undo = true;                /* all editing is enabled for DA windows */
  856.         cutCopyClear = true;
  857.         paste = true;
  858.     } else if ( IsAppWindow(window) ) {
  859.         te = ((DocumentPeek) window)->docTE;
  860.         if ( (*te)->selStart < (*te)->selEnd )
  861.             cutCopyClear = true;
  862.             /* Cut, Copy, and Clear is enabled for app. windows with selections */
  863.         if ( GetScrap(nil, 'TEXT', &offset)  > 0)
  864.             paste = true;            /* if there’s any text in the clipboard, paste is enabled */
  865.     }
  866.     if ( undo )
  867.         EnableItem(menu, iUndo);
  868.     else
  869.         DisableItem(menu, iUndo);
  870.     if ( cutCopyClear ) {
  871.         EnableItem(menu, iCut);
  872.         EnableItem(menu, iCopy);
  873.         EnableItem(menu, iClear);
  874.     } else {
  875.         DisableItem(menu, iCut);
  876.         DisableItem(menu, iCopy);
  877.         DisableItem(menu, iClear);
  878.     }
  879.     if ( paste )
  880.         EnableItem(menu, iPaste);
  881.     else
  882.         DisableItem(menu, iPaste);
  883.  
  884.  
  885.     /* Setup font and size menus */
  886.     menu = GetMHandle(mFont);
  887.     items = CountMItems(menu);
  888.     if (IsAppWindow (window))
  889.     {
  890.         te = ((DocumentPeek) window)->docTE;
  891.         TEGetStyle((*te)->selStart, &theStyle, &lHeight, &lAscent, te);
  892.     }
  893.     else
  894.     {
  895.         theStyle.tsFont = -1;
  896.         theStyle.tsSize = 0;
  897.     }
  898.     for (loop = 0; loop < items; loop++)
  899.     {
  900.         GetItem(menu, loop, theName);
  901.         GetFNum(theName, &font_num);
  902.         CheckItem(menu, loop, font_num == theStyle.tsFont);
  903.     }
  904.         
  905.     menu = GetMHandle(mSize);
  906.     NumToString(theStyle.tsSize, theName);
  907.     SetItem(menu, 2, theName);
  908. } /*AdjustMenus*/
  909.  
  910.  
  911. /*    This is called when an item is chosen from the menu bar (after calling
  912.     MenuSelect or MenuKey). It does the right thing for each command. */
  913.  
  914. void DoMenuCommand(menuResult)
  915.     long        menuResult;
  916. {
  917.     short        menuID, menuItem;
  918.     short        itemHit, daRefNum;
  919.     Str255        daName;
  920.     OSErr        saveErr;
  921.     TEHandle    te;
  922.     WindowPtr    window;
  923.     Handle        aHandle;
  924.     long        oldSize, newSize;
  925.     long        total, contig;
  926.  
  927.     window = FrontWindow();
  928.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  929.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  930.     switch ( menuID ) {
  931.         case mApple:
  932.             switch ( menuItem ) {
  933.                 case iAbout:        /* bring up alert for About */
  934.                     itemHit = Alert(rAboutAlert, nil);
  935.                     break;
  936.                 default:            /* all non-About items in this menu are DAs et al */
  937.                     /* type Str255 is an array in MPW 3 */
  938.                     GetItem(GetMHandle(mApple), menuItem, daName);
  939.                     daRefNum = OpenDeskAcc(daName);
  940.                     break;
  941.             }
  942.             break;
  943.         case mFile:
  944.             switch ( menuItem ) {
  945.                 case iNew:
  946.                     DoNew();
  947.                     break;
  948.                 case iOpen:
  949.                     SetCursor(*WATCH);
  950.  
  951.                     /* ••• The following lines were added for XTND ••• */
  952.  
  953.                     DoOpen();
  954.  
  955.                     /* ••• End of XTND additions ••• */
  956.  
  957.                     break;
  958.                 case iSave:
  959.                 case iSaveAs:
  960.  
  961.                     /* ••• The following lines were added for XTND ••• */
  962.  
  963.                     DoSave(menuItem == iSaveAs);
  964.  
  965.                     /* ••• End of XTND additions ••• */
  966.  
  967.                     break;
  968.                 case iClose:
  969.                     DoCloseWindow(FrontWindow());            /* ignore the result */
  970.                     break;
  971.                 case iQuit:
  972.                     Terminate();
  973.                     break;
  974.             }
  975.             SetCursor(&arrow);
  976.             break;
  977.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  978.             if ( !SystemEdit(menuItem-1) ) {
  979.                 te = ((DocumentPeek) FrontWindow())->docTE;
  980.                 switch ( menuItem ) {
  981.                     case iCut:
  982.                         if ( ZeroScrap() == noErr ) {
  983.                             PurgeSpace(&total, &contig);
  984.                             if ((*te)->selEnd - (*te)->selStart + kTESlop > contig)
  985.                                 AlertUser(eNoSpaceCut,0);
  986.                             else 
  987.                                 {
  988.                                 TECut(te);
  989.                                 if ( TEToScrap() != noErr ) {
  990.                                     AlertUser(eNoCut,0);
  991.                                     ZeroScrap();
  992.                                 }
  993.                             }
  994.                         }
  995.                         break;
  996.                     case iCopy:
  997.                         if ( ZeroScrap() == noErr ) {
  998.                             TECopy(te);    /* after copying, export the TE scrap */
  999.                             if ( TEToScrap() != noErr ) {
  1000.                                 AlertUser(eNoCopy,0);
  1001.                                 ZeroScrap();
  1002.                             }
  1003.                         }
  1004.                         break;
  1005.                     case iPaste:    /* import the TE scrap before pasting */
  1006.                         if ( TEFromScrap() == noErr ) {
  1007.                             if ( TEGetScrapLen() + ((*te)->teLength -
  1008.                                 ((*te)->selEnd - (*te)->selStart)) > kMaxTELength )
  1009.                                 AlertUser(eExceedPaste,0);
  1010.                             else {
  1011.                                 aHandle = (Handle) TEGetText(te);
  1012.                                 oldSize = GetHandleSize(aHandle);
  1013.                                 newSize = oldSize + TEGetScrapLen() + kTESlop;
  1014.                                 SetHandleSize(aHandle, newSize);
  1015.                                 saveErr = MemError();
  1016.                                 SetHandleSize(aHandle, oldSize);
  1017.                                 if (saveErr != noErr)
  1018.                                     AlertUser(eNoSpacePaste,0);
  1019.                                 else
  1020.                                     TEStylPaste(te);
  1021.                             }
  1022.                         }
  1023.                         else
  1024.                             AlertUser(eNoPaste,0);
  1025.                         break;
  1026.                     case iClear:
  1027.                         TEDelete(te);
  1028.                         break;
  1029.                 }
  1030.             AdjustScrollbars(window, false);
  1031.             AdjustTE(window);
  1032.             }
  1033.             break;
  1034.         
  1035.     }
  1036.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  1037. } /*DoMenuCommand*/
  1038.  
  1039.  
  1040. /* Create a new document and window. */
  1041.  
  1042. void DoNew()
  1043. {
  1044.     Boolean        good;
  1045.     Ptr            storage;
  1046.     WindowPtr    window;
  1047.     Rect        destRect, viewRect;
  1048.     RGBColor    newColor;
  1049.     TextStyle     newStyle;
  1050.     DocumentPeek doc;
  1051.  
  1052.     storage = NewPtr(sizeof(DocumentRecord));
  1053.     if ( storage != nil ) {
  1054.         window = GetNewWindow(rDocWindow, storage, (WindowPtr) -1);
  1055.         if ( window != nil ) {
  1056.             gNumDocuments += 1;            /* this will be decremented when we call DoCloseWindow */
  1057.             good = false;
  1058.             SetPort(window);
  1059.             doc =  (DocumentPeek) window;
  1060.             GetTERect(window, &viewRect);
  1061.             destRect = viewRect;
  1062.             destRect.right = destRect.left + kMaxDocWidth;
  1063.             doc->docTE = TEStylNew(&destRect, &viewRect);
  1064.             good = doc->docTE != nil;    /* if TENew succeeded, we have a good document */
  1065.             if ( good ) {                /* 1.02 - good document? — proceed */
  1066.                 TECalText(doc->docTE);                                /*fixes bug that sets cursor to random height*/
  1067.                 doc->docClik = (ProcPtr) (*doc->docTE)->clikLoop;
  1068.                 SetClikLoop((ClikLoopProcPtr)ASMCLIKLOOP, doc->docTE);
  1069.  
  1070.                 newColor.red = 0;                            /* selected color defaults to black */
  1071.                 newColor.green = 0;
  1072.                 newColor.blue = 0;
  1073.             
  1074.                 newStyle.tsFont = applFont;                    /*initial text style*/
  1075.                 newStyle.tsFace = normal;
  1076.                 newStyle.tsSize = 12;
  1077.                 newStyle.tsColor = newColor;
  1078.             
  1079.                 TESetStyle(doAll, &newStyle, true, doc->docTE);
  1080.     
  1081.             }
  1082.             
  1083.             if ( good ) {                /* good document? — get scrollbars */
  1084.                 doc->docVScroll = GetNewControl(rVScroll, window);
  1085.                 good = (doc->docVScroll != nil);
  1086.             }
  1087.             if ( good) {
  1088.                 doc->docHScroll = GetNewControl(rHScroll, window);
  1089.                 good = (doc->docHScroll != nil);
  1090.             }
  1091.             
  1092.             if ( good ) {                /* good? — adjust & draw the controls, draw the window */
  1093.                 /* false to AdjustScrollValues means musn’t redraw; technically, of course,
  1094.                 the window is hidden so it wouldn’t matter whether we called ShowControl or not. */
  1095.                 AdjustScrollValues(window, false);
  1096.                 ShowWindow(window);
  1097.             } else {
  1098.                 DoCloseWindow(window);    /* otherwise regret we ever created it... */
  1099.                 AlertUser(eNoWindow,0);            /* and tell user */
  1100.             }
  1101.         } else
  1102.             DisposPtr(storage);            /* get rid of the storage if it is never used */
  1103.     }
  1104. } /*DoNew*/
  1105.  
  1106.  
  1107. /* Close a window. This handles desk accessory and application windows. */
  1108.  
  1109. /*    1.01 - At this point, if there was a document associated with a
  1110.     window, you could do any document saving processing if it is 'dirty'.
  1111.     DoCloseWindow would return true if the window actually closed, i.e.,
  1112.     the user didn’t cancel from a save dialog. This result is handy when
  1113.     the user quits an application, but then cancels the save of a document
  1114.     associated with a window. */
  1115.  
  1116. Boolean DoCloseWindow(window)
  1117.     WindowPtr    window;
  1118. {
  1119.     TEHandle    te;
  1120.  
  1121.     if ( IsDAWindow(window) )
  1122.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  1123.     else if ( IsAppWindow(window) ) {
  1124.         te = ((DocumentPeek) window)->docTE;
  1125.         if ( te != nil )
  1126.             TEDispose(te);            /* dispose the TEHandle if we got far enough to make one */
  1127.         /*    1.01 - We used to call DisposeWindow, but that was technically
  1128.             incorrect, even though we allocated storage for the window on
  1129.             the heap. We should instead call CloseWindow to have the structures
  1130.             taken care of and then dispose of the storage ourselves. */
  1131.         CloseWindow(window);
  1132.         DisposPtr((Ptr) window);
  1133.         gNumDocuments -= 1;
  1134.     }
  1135.     return true;
  1136. } /*DoCloseWindow*/
  1137.  
  1138.  
  1139. /**************************************************************************************
  1140. *** 1.01 DoCloseBehind(window) was removed ***
  1141.  
  1142.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  1143.     and not having to worry about updating the windows, but it suffered
  1144.     from a fatal flaw. If a desk accessory owned two windows, it would
  1145.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  1146.     got around to calling DoCloseWindow for that other window that was already
  1147.     closed, things would go very poorly. Another option would be to have a
  1148.     procedure, GetRearWindow, that would go through the window list and return
  1149.     the last window. Instead, we decided to present the standard approach
  1150.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  1151.     has a potential benefit in that the window whose document needs to be saved
  1152.     may be visible since it is the front window, therefore decreasing the
  1153.     chance of user confusion. For aesthetic reasons, the windows in the
  1154.     application should be checked for updates periodically and have the
  1155.     updates serviced.
  1156. **************************************************************************************/
  1157.  
  1158.  
  1159. /* Clean up the application and exit. We close all of the windows so that
  1160.  they can update their documents, if any. */
  1161.  
  1162. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  1163.     shell, but will return instead. */
  1164.  
  1165. void Terminate()
  1166. {
  1167.     WindowPtr    aWindow;
  1168.     Boolean        closed;
  1169.     
  1170.     closed = true;
  1171.     do {
  1172.         aWindow = FrontWindow();                /* get the current front window */
  1173.         if (aWindow != nil)
  1174.             closed = DoCloseWindow(aWindow);    /* close this window */    
  1175.     }
  1176.     while (closed && (aWindow != nil));
  1177.     if (closed)
  1178.     {
  1179.         /* ••• The following lines were added for XTND ••• */
  1180.  
  1181.         XTNDCloseTranslators();                    /* XTND Library Tidy Up */
  1182.  
  1183.         /* ••• End of XTND additions ••• */
  1184.  
  1185.         ExitToShell();                            /* exit if no cancellation */
  1186.     }
  1187. } /*Terminate*/
  1188.  
  1189.  
  1190. /* Return a rectangle that is inset from the portRect by the size of
  1191.     the scrollbars and a little extra margin. */
  1192.  
  1193. void GetTERect(window,teRect)
  1194.     WindowPtr    window;
  1195.     Rect        *teRect;
  1196. {
  1197.     *teRect = window->portRect;
  1198.     InsetRect(teRect, kTextMargin, kTextMargin);    /* adjust for margin */
  1199.     teRect->bottom = teRect->bottom - 15;        /* and for the scrollbars */
  1200.     teRect->right = teRect->right - 15;
  1201. } /*GetTERect*/
  1202.  
  1203.  
  1204. /* Scroll the TERec around to match up to the potentially updated scrollbar
  1205.     values. This is really useful when the window has been resized such that the
  1206.     scrollbars became inactive but the TERec was already scrolled. */
  1207.  
  1208. void AdjustTE(window)
  1209.     WindowPtr    window;
  1210. {
  1211.     TEPtr        te;
  1212.     
  1213.     te = *((DocumentPeek)window)->docTE;
  1214.     TEScroll((te->viewRect.left - te->destRect.left) -
  1215.             GetCtlValue(((DocumentPeek)window)->docHScroll),
  1216.             (te->viewRect.top - te->destRect.top) -
  1217.                 GetCtlValue(((DocumentPeek)window)->docVScroll),
  1218.             ((DocumentPeek)window)->docTE);
  1219. } /*AdjustTE*/
  1220.  
  1221.  
  1222. /* Calculate the new control maximum value and current value, whether it is the horizontal or
  1223.     vertical scrollbar. The vertical max is calculated by comparing the number of lines to the
  1224.     vertical size of the viewRect. The horizontal max is calculated by comparing the maximum document
  1225.     width to the width of the viewRect. The current values are set by comparing the offset between
  1226.     the view and destination rects. If necessary and we canRedraw, have the control be re-drawn by
  1227.     calling ShowControl. */
  1228.  
  1229. void AdjustHV(isVert,control,docTE,canRedraw)
  1230.     Boolean        isVert;
  1231.     ControlHandle control;
  1232.     TEHandle    docTE;
  1233.     Boolean        canRedraw;
  1234. {
  1235.     short        value, max, windowHeight, textHeight, lineHt, fontAsc;
  1236.     short        oldValue, oldMax;
  1237.     TEPtr        te;
  1238.     TextStyle tempStyle;
  1239.     
  1240.     oldValue = GetCtlValue(control);
  1241.     oldMax = GetCtlMax(control);
  1242.     te = *docTE;                            /* point to TERec for convenience */
  1243.     if ( isVert ) {
  1244.         windowHeight = te->viewRect.bottom - te->viewRect.top;
  1245.         textHeight = TEGetHeight(1, te->nLines, docTE);
  1246.         
  1247.         if (te->teLength > 0) {
  1248.             if ( *(*te->hText + te->teLength - 1) == kCrChar ) {
  1249.                 TEGetStyle(te->teLength - 1, &tempStyle, &lineHt, &fontAsc, docTE);
  1250.                 textHeight = textHeight + lineHt;
  1251.             }
  1252.         }
  1253.         max = textHeight - windowHeight;
  1254.     } else
  1255.         max = kMaxDocWidth - (te->viewRect.right - te->viewRect.left);
  1256.     
  1257.     if ( max < 0 ) max = 0;
  1258.     SetCtlMax(control, max);
  1259.     
  1260.     /* Must deref. after SetCtlMax since, technically, it could draw and therefore move
  1261.         memory. This is why we don’t just do it once at the beginning. */
  1262.     te = *docTE;
  1263.     if ( isVert )
  1264.         value = te->viewRect.top - te->destRect.top;
  1265.     else
  1266.         value = te->viewRect.left - te->destRect.left;
  1267.     
  1268.     if ( value < 0 ) value = 0;
  1269.     else if ( value >  max ) value = max;
  1270.     
  1271.     SetCtlValue(control, value);
  1272.     /* now redraw the control if it needs to be and can be */
  1273.     if ( canRedraw || (max != oldMax) || (value != oldValue) )
  1274.         ShowControl(control);
  1275. } /*AdjustHV*/
  1276.  
  1277.  
  1278. /* Simply call the common adjust routine for the vertical and horizontal scrollbars. */
  1279.  
  1280. void AdjustScrollValues(window,canRedraw)
  1281.     WindowPtr    window;
  1282.     Boolean        canRedraw;
  1283. {
  1284.     DocumentPeek doc;
  1285.     
  1286.     doc = (DocumentPeek)window;
  1287.     AdjustHV(true, doc->docVScroll, doc->docTE, canRedraw);
  1288.     AdjustHV(false, doc->docHScroll, doc->docTE, canRedraw);
  1289. } /*AdjustScrollValues*/
  1290.  
  1291.  
  1292. /*    Re-calculate the position and size of the viewRect and the scrollbars.
  1293.     kScrollTweek compensates for off-by-one requirements of the scrollbars
  1294.     to have borders coincide with the growbox. */
  1295.  
  1296. void AdjustScrollSizes(window)
  1297.     WindowPtr    window;
  1298. {
  1299.     Rect        teRect;
  1300.     DocumentPeek doc;
  1301.     
  1302.     doc = (DocumentPeek) window;
  1303.     GetTERect(window, &teRect);                            /* start with TERect */
  1304.     (*doc->docTE)->viewRect = teRect;
  1305.     MoveControl(doc->docVScroll, window->portRect.right - kScrollbarAdjust, -1);
  1306.     SizeControl(doc->docVScroll, kScrollbarWidth, (window->portRect.bottom - 
  1307.                 window->portRect.top) - (kScrollbarAdjust - kScrollTweek));
  1308.     MoveControl(doc->docHScroll, -1, window->portRect.bottom - kScrollbarAdjust);
  1309.     SizeControl(doc->docHScroll, (window->portRect.right - 
  1310.                 window->portRect.left) - (kScrollbarAdjust - kScrollTweek),
  1311.                 kScrollbarWidth);
  1312. } /*AdjustScrollSizes*/
  1313.  
  1314.  
  1315. /* Turn off the controls by jamming a zero into their contrlVis fields (HideControl erases them
  1316.     and we don't want that). If the controls are to be resized as well, call the procedure to do that,
  1317.     then call the procedure to adjust the maximum and current values. Finally re-enable the controls
  1318.     by jamming a $FF in their contrlVis fields. */
  1319.  
  1320. void AdjustScrollbars(window,needsResize)
  1321.     WindowPtr    window;
  1322.     Boolean        needsResize;
  1323. {
  1324.     DocumentPeek doc;
  1325.     
  1326.     doc = (DocumentPeek) window;
  1327.     /* First, turn visibility of scrollbars off so we won’t get unwanted redrawing */
  1328.     (*doc->docVScroll)->contrlVis = kControlInvisible;    /* turn them off */
  1329.     (*doc->docHScroll)->contrlVis = kControlInvisible;
  1330.     if ( needsResize )                                    /* move & size as needed */
  1331.         AdjustScrollSizes(window);
  1332.     AdjustScrollValues(window, needsResize);            /* fool with max and current value */
  1333.     /* Now, restore visibility in case we never had to ShowControl during adjustment */
  1334.     (*doc->docVScroll)->contrlVis = kControlVisible;    /* turn them on */
  1335.     (*doc->docHScroll)->contrlVis = kControlVisible;
  1336. } /* AdjustScrollbars */
  1337.  
  1338.  
  1339. /* Gets called from our assembly language routine, ASMCLIKLOOP, which is in
  1340.     turn called by the TEClick toolbox routine. Saves the windows clip region,
  1341.     sets it to the portRect, adjusts the scrollbar values to match the TE scroll
  1342.     amount, then restores the clip region. */
  1343.  
  1344. pascal  void PASCALCLIKLOOP()
  1345. {
  1346.     WindowPtr    window;
  1347.     RgnHandle    region;
  1348.     
  1349.     window = FrontWindow();
  1350.     region = NewRgn();
  1351.     GetClip(region);                    /* save clip */
  1352.     ClipRect(&window->portRect);
  1353.     AdjustScrollValues(window, true);    /* pass true for canRedraw */
  1354.     SetClip(region);                    /* restore clip */
  1355.     DisposeRgn(region);
  1356. } /* PASCALCLIKLOOP */
  1357.  
  1358.  
  1359. /* Gets called from our assembly language routine, ASMCLIKLOOP, which is in
  1360.     turn called by the TEClick toolbox routine. It returns the address of the
  1361.     default clikLoop routine that was put into the TERec by TEAutoView to
  1362.     ASMCLIKLOOP so that it can call it. */
  1363.  
  1364. pascal ProcPtr GETOLDCLIKLOOP()
  1365. {
  1366.     return ((DocumentPeek)FrontWindow())->docClik;
  1367. } /* GETOLDCLIKLOOP */
  1368.  
  1369.  
  1370. /*    Check to see if a window belongs to the application. If the window pointer
  1371.     passed was NIL, then it could not be an application window. WindowKinds
  1372.     that are negative belong to the system and windowKinds less than userKind
  1373.     are reserved by Apple except for windowKinds equal to dialogKind, which
  1374.     mean it is a dialog.
  1375.     1.02 - In order to reduce the chance of accidentally treating some window
  1376.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  1377.     is userKind. If you add different kinds of windows to Sample you'll need
  1378.     to change how this all works. */
  1379.  
  1380. Boolean IsAppWindow(window)
  1381.     WindowPtr    window;
  1382. {
  1383.     short        windowKind;
  1384.  
  1385.     if ( window == nil )
  1386.         return false;
  1387.     else {    /* application windows have windowKinds = userKind (8) */
  1388.         windowKind = ((WindowPeek) window)->windowKind;
  1389.         return (windowKind == userKind);
  1390.     }
  1391. } /*IsAppWindow*/
  1392.  
  1393.  
  1394. /* Check to see if a window belongs to a desk accessory. */
  1395.  
  1396. Boolean IsDAWindow(window)
  1397.     WindowPtr    window;
  1398. {
  1399.     if ( window == nil )
  1400.         return false;
  1401.     else    /* DA windows have negative windowKinds */
  1402.         return ((WindowPeek) window)->windowKind < 0;
  1403. } /*IsDAWindow*/
  1404.  
  1405.  
  1406. /*    Display an alert that tells the user an error occurred, then exit the program.
  1407.     This routine is used as an ultimate bail-out for serious errors that prohibit
  1408.     the continuation of the application. Errors that do not require the termination
  1409.     of the application should be handled in a different manner. Error checking and
  1410.     reporting has a place even in the simplest application. The error number is used
  1411.     to index an 'STR#' resource so that a relevant message can be displayed. */
  1412.  
  1413.  
  1414. void AlertUser(error,code)
  1415.     short        error, code;
  1416. {
  1417.     short        itemHit;
  1418.     Str255        message, tempStr;
  1419.  
  1420.     SetCursor(&arrow);
  1421.     /* type Str255 is an array in MPW 3 */
  1422.     GetIndString(message, kErrStrings, error);
  1423.     if (code != 0) {
  1424.         NumToString(code, tempStr);
  1425.         ParamText(message, tempStr, (StringPtr)"\p", (StringPtr)"\p");
  1426.     }
  1427.     else
  1428.         ParamText(message, (StringPtr)"\p", (StringPtr)"\p", (StringPtr)"\p");
  1429.     itemHit = Alert(rUserAlert, nil);
  1430. } /* AlertUser */
  1431.  
  1432.  
  1433. /*    Set up the whole world, including global variables, Toolbox managers,
  1434.     menus, and a single blank document. */
  1435.  
  1436. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  1437.     this module. If an error is detected, instead of merely doing an ExitToShell,
  1438.     which leaves the user without much to go on, we call AlertUser, which puts
  1439.     up a simple alert that just says an error occurred and then calls ExitToShell.
  1440.     Since there is no other cleanup needed at this point if an error is detected,
  1441.     this form of error- handling is acceptable. If more sophisticated error recovery
  1442.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  1443.  
  1444. #pragma segment Initialize
  1445. void Initialize()
  1446. {
  1447.     Handle    menuBar;
  1448.     long    total, contig;
  1449.     EventRecord event;
  1450.     short    count;
  1451.  
  1452.     gInBackground = false;
  1453.  
  1454.     InitGraf((Ptr) &thePort);
  1455.     InitFonts();
  1456.     InitWindows();
  1457.     InitMenus();
  1458.     TEInit();
  1459.     InitDialogs(nil);
  1460.     InitCursor();
  1461.     WATCH = GetCursor(watchCursor);
  1462.     SetCursor(*WATCH);
  1463.  
  1464.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  1465.          if you are using it. */
  1466.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  1467.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  1468.         of checking for port availability themselves. */
  1469.     
  1470.     /*    This next bit of code is necessary to allow the default button of our
  1471.         alert be outlined.
  1472.         1.02 - Changed to call EventAvail so that we don't lose some important
  1473.         events. */
  1474.      
  1475.     for (count = 1; count <= 3; count++)
  1476.         EventAvail(everyEvent, &event);
  1477.     
  1478.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  1479.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  1480.         call to SysEnvirons by calling it after initializing AppleTalk. */
  1481.      
  1482.     SysEnvirons(kSysEnvironsVersion, &gMac);
  1483.     
  1484.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  1485.     
  1486.     if (gMac.machineType < 0) BigBadError(eWrongMachine);
  1487.     
  1488.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  1489.         in TrapAvailable if a tool trap value is out of range. */
  1490.         
  1491.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  1492.  
  1493.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  1494.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  1495.         MultiFinder we needed. This did not work well because it assumed too much about
  1496.         the relationship between what we asked MultiFinder for and what we would actually
  1497.         get back, as well as how to measure it. Instead, we will use an alternate
  1498.         method comprised of two steps. */
  1499.      
  1500.     /*    It is better to first check the size of the application heap against a value
  1501.         that you have determined is the smallest heap the application can reasonably
  1502.         work in. This number should be derived by examining the size of the heap that
  1503.         is actually provided by MultiFinder when the minimum size requested is used.
  1504.         The derivation of the minimum size requested from MultiFinder is described
  1505.         in Sample.h. The check should be made because the preferred size can end up
  1506.         being set smaller than the minimum size by the user. This extra check acts to
  1507.         insure that your application is starting from a solid memory foundation. */
  1508.      
  1509.     if ((long) GetApplLimit() - (long) ApplicZone() < kMinHeap) BigBadError(eSmallSize);
  1510.     
  1511.     /*    Next, make sure that enough memory is free for your application to run. It
  1512.         is possible for a situation to arise where the heap may have been of required
  1513.         size, but a large scrap was loaded which left too little memory. To check for
  1514.         this, call PurgeSpace and compare the result with a value that you have determined
  1515.         is the minimum amount of free memory your application needs at initialization.
  1516.         This number can be derived several different ways. One way that is fairly
  1517.         straightforward is to run the application in the minimum size configuration
  1518.         as described previously. Call PurgeSpace at initialization and examine the value
  1519.         returned. However, you should make sure that this result is not being modified
  1520.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  1521.         PurgeSpace. Make sure to remove that call before shipping, though. */
  1522.     
  1523.     /* ZeroScrap(); */
  1524.  
  1525.     PurgeSpace(&total, &contig);
  1526.     if (total < kMinSpace)
  1527.         if (UnloadScrap() != noErr)
  1528.             BigBadError(eNoMemory);
  1529.         else {
  1530.             PurgeSpace(&total, &contig);
  1531.             if (total < kMinSpace)
  1532.                 BigBadError(eNoMemory);
  1533.         }
  1534.  
  1535.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  1536.         to check memory is that we can now give the user an alert to tell him/her what
  1537.         happened. Although it is possible that the memory situation could be worsened by
  1538.         displaying an alert, MultiFinder would gracefully exit the application with
  1539.         an informative alert if memory became critical. Here we are acting more
  1540.         in a preventative manner to avoid future disaster from low-memory problems. */
  1541.  
  1542.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  1543.     if ( menuBar == nil )
  1544.                 BigBadError(eNoMemory);
  1545.     SetMenuBar(menuBar);                    /* install menus */
  1546.     DisposHandle(menuBar);
  1547.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  1548.     AddResMenu(GetMHandle(mFont), 'FONT');    /* add FONT names to Font menu */
  1549.     DrawMenuBar();
  1550.  
  1551.     gNumDocuments = 0;
  1552.  
  1553.     /* do other initialization here */
  1554.  
  1555.     /* ••• The following lines were added for XTND ••• */
  1556.  
  1557.     XTNDInit();
  1558.     SetCursor(&arrow);
  1559.     
  1560.     /* ••• End of XTND additions ••• */
  1561.  
  1562.     DoNew();                                /* create a single empty document */
  1563.     
  1564. } /*Initialize*/
  1565.  
  1566.  
  1567. /* Used whenever a, like, fully fatal error happens */
  1568. void BigBadError(error)
  1569.     short error;
  1570. {
  1571.     AlertUser(error,0);
  1572.  
  1573.     /* ••• The following lines were added for XTND ••• */
  1574.  
  1575.     XTNDCloseTranslators();                    /* XTND Library Tidy Up */
  1576.     
  1577.     /* ••• End of XTND additions ••• */
  1578.  
  1579.     ExitToShell();
  1580. }
  1581.  
  1582. /*    Check to see if a given trap is implemented. This is only used by the
  1583.     Initialize routine in this program, so we put it in the Initialize segment.
  1584.     The recommended approach to see if a trap is implemented is to see if
  1585.     the address of the trap routine is the same as the address of the
  1586.     Unimplemented trap. */
  1587. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  1588.     if a ToolTrap is out of range of a pre-MacII ROM. */
  1589.  
  1590. Boolean TrapAvailable(tNumber,tType)
  1591.     short        tNumber;
  1592.     TrapType    tType;
  1593. {
  1594.     if ( ( tType == (unsigned char) ToolTrap ) &&
  1595.         ( gMac.machineType > envMachUnknown ) &&
  1596.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  1597.         tNumber = tNumber & 0x03FF;
  1598.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  1599.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  1600.     }
  1601.     return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
  1602. } /*TrapAvailable*/
  1603.